// @flow
import React, { Component } from 'react'
import styles from './ModelDetail.css'
import { Switch, message } from 'antd'
import moment from 'moment'
import universalFetch, { handleFetchError } from 'store/modules/fetch'

type Props = {
  algInfo: Object
}
type State = {
  useFul: boolean
}

class ModelDetail extends Component {
  props: Props
  state: State
  closeModel: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      useFul: false
    }
    this.closeModel = this.closeModel.bind(this)
  }
  componentWillReceiveProps (nextProps: Props) {
    this.setState({
      useFul: nextProps.algInfo.useFul
    })
  }
  closeModel (checked) {
    const { algInfo } = this.props
    universalFetch(`${__SERVICE_API__}analysis/models/${algInfo.id}?useful=${checked}&isTemplate=true`,
      {
        method: 'PUT'
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          useFul: !this.state.useFul
        })
        message.success('操作成功')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.error('操作失败')
      })
  }
  render () {
    const { algInfo } = this.props
    const { useFul } = this.state
    return (
      <div className={styles['detail-main']}>
        <header className={styles['alg-header']}>
          <div className={styles['alg-title']}>
            <h2>{algInfo.name}</h2>
            <div className={styles['alg-title-desc']}>
              数据源: {algInfo.dataSource}
              &nbsp;&nbsp;
              分析类型：{algInfo.analysisType}
              &nbsp;&nbsp;
              创建于: <span className={styles['time']}>{moment(algInfo.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
              &nbsp;&nbsp;
              更新于: <span className={styles['time']}>{moment(algInfo.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
            </div>
          </div>
          <div className={styles['alg-link']} style={{ background: 'none' }}>
            {
              // <a href={algInfo.downloadUrl} style={{ color:'#108ee9', marginRight: 10 }}>下载模型</a>
            }
            <Switch checkedChildren={'可用'} unCheckedChildren={'失效'}
              onChange={this.closeModel} checked={useFul} />
          </div>

        </header>
        <div className={styles['alg-content']}>
          <div className={styles['alg-img']}>
            <img src={`${algInfo.imgUrl}`} />
          </div>
          <div className={styles['alg-desc']}>
            <h3>模型介绍:</h3>
            <p className={styles['alg-desc-content']}>{algInfo.shortDesc}</p>
          </div>
        </div>
      </div>
    )
  }
}

export default ModelDetail
